package cn.jsc.org.service.impl;

import cn.jsc.basic.service.impl.BaseServiceImpl;
import cn.jsc.org.domain.Department;
import cn.jsc.org.mapper.DepartmentMapper;
import cn.jsc.org.service.IDepartmentServiceI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
/**
 * 部门服务层
 */
@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentServiceI {
    @Autowired
    private DepartmentMapper departmentMapper;
    @Override
    @Transactional
    public void add(Department department) {
        //思路.传进来 如果有parentId有效值就维护  没有主键id
        //1.保存到数据库  还要拿到主键id  因为要去维护dirPath
        departmentMapper.save(department);
        /*直接在这调用修改就会执行*/
        this.update(department);
    }

    @Override
    @Transactional
    public void update(Department department) {
        //思路.传进来 如果有parentId有效值就维护  没有主键id
        //1.保存到数据库  还要拿到主键id  因为要去维护dirPath
        //2.判断是否配置了父部门
        String dirPath = "";
        if (department.getParent() != null && department.getParent().getId() != null){
            //2.1如果配置了  根据父部门查询父部门的dirPath 拼上当前的id
            Long parId = department.getParent().getId();
            Department parDept = departmentMapper.loadById(parId);
            //父亲的dirPath+当前对象的主键id
            dirPath = parDept.getDirPath()+"/"+department.getId();
        }else {
            //2.2如果没有父部门，我就是顶级  “/”+当前id
            dirPath = "/"+department.getId();
        }
        //3把dirPath字段入库
        department.setDirPath(dirPath);
        departmentMapper.update(department);
    }

    @Override
    public List<Department> queryTree() {
        return departmentMapper.queryTree();
    }


}
